package com.odin.backgrounddownload.downloader;

import android.app.Activity;
import android.os.Build;

import com.odin.backgrounddownload.DownloadParam;
import com.odin.backgrounddownload.SGActivityLifecycleCallbacks;

import java.io.File;
import java.text.DecimalFormat;

public abstract class SGBaseBackGroundDownload
{
    protected Activity m_UnityMainActivity;
    protected String m_CdnUrl;
    protected String m_PersistentPath;
    private boolean m_IsFocus;
    protected int m_MaxDownloadingCount = 5;
    // 边玩边下 下载间隔时间（单位：秒）
    protected float m_SilentIntervalTime = 5;
    // 边玩边下 每批大小（单位：MB）
    protected long m_SilentBatchSize = 5;
    protected SGNotificationHelper m_SGNotificationHelper;
    protected SGBackGroundDownloadCallback m_SGBackGroundDownloadCallback;
    private SGActivityLifecycleCallbacks m_SGActivityLifecycleCallbacks;

    public SGBaseBackGroundDownload(Activity activity, String cdnUrl, String persistentPath, SGBackGroundDownloadCallback callback)
    {
        m_UnityMainActivity = activity;
        m_CdnUrl = cdnUrl;
        m_PersistentPath = persistentPath;
        m_SGNotificationHelper = new SGNotificationHelper(m_UnityMainActivity);
        m_SGBackGroundDownloadCallback = callback;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
        {
            // 监听 app 是否切换到后台
            m_SGActivityLifecycleCallbacks = new SGActivityLifecycleCallbacks(new SGActivityLifecycleCallbacks.BooleanChangedCallbacks() {
                @Override
                public void onFocusChanged(boolean newValue) {
                    OnAppFocus(newValue);
                }
            });
            m_UnityMainActivity.registerActivityLifecycleCallbacks(m_SGActivityLifecycleCallbacks);
        }
    }

    // region 虚函数
    public abstract void AddDownload(DownloadParam[] downloadParams);
    public abstract void ForceDownload(DownloadParam downloadParam);
    public abstract void StartDownload();
    public abstract void PauseDownload();
    public abstract long GetDownloadedSize();
    public abstract long GetAllDownloadSize();
    public abstract int QueryDownloadStatus(String urlRelativePath);
    // endregion

    public void SetBackGroundDownloadParams(int maxDownloadingCount, float silentIntervalTime, long silentBatchSize)
    {
        m_MaxDownloadingCount = maxDownloadingCount;
        m_SilentBatchSize = silentBatchSize;
        m_SilentIntervalTime = silentIntervalTime;
    }

    protected void UpadteNotice()
    {
        if (!m_IsFocus)
        {
            // 更新下载进度
            String content = FormatFileSize(GetDownloadedSize()) + "/" + FormatFileSize(GetAllDownloadSize());
            m_SGNotificationHelper.UpdateNotification(content);
        }
    }

    protected long GetFileSize(String filePath)
    {
        File file = new File(filePath);
        return file.length();
    }

    protected String FormatFileSize(long size) {
        if (size <= 0) return "0 B";
        final String[] units = new String[] { "B", "KB", "MB", "GB", "TB" };
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    protected String AppendPath(String path1, String path2)
    {
        if (path1.endsWith("/") || path2.startsWith("/"))
        {
            return path1 + path2;
        }
        return path1 + "/" + path2;
    }

    //region 事件处理
    private void OnAppFocus(boolean isFocus){
        m_IsFocus = isFocus;
        if (m_IsFocus)
        {
            m_SGNotificationHelper.CancelNotification();
        }
    }
    //endregion
}
